<template>
  <div class="private-message">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <h2>{{ targetUser.user_name }}</h2>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="chatMessages">
      <div
        v-for="message in messages"
        :key="message.id"
        class="message-card"
        :class="{ 'my-message': message.sender === String(user_id), 'other-message': message.sender !== String(user_id) }"
      >
        <!-- 用户头像 -->
        <div v-if="message.sender === String(user_id)" class="message-avatar my-avatar">
          <img :src="'http://localhost:8080/images/upload/' + profile_picture" alt="头像" />
        </div>
        <div v-else class="message-avatar other-avatar">
          <img :src="'http://localhost:8080/images/upload/' + targetUser.profile_picture" alt="头像" />
        </div>

        <!-- 消息卡片 -->
        <div class="message-card-body">
          <div class="message-content">{{ message.content }}</div>
          <div class="message-meta">
            <span class="message-timestamp">{{ formatDate(message.timestamp) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天输入区域 -->
    <div class="chat-input">
      <input
        type="text"
        v-model="newMessage"
        placeholder="输入消息..."
        @keydown.enter="sendMessage"
      />
      <button @click="sendMessage" :disabled="loading">
        {{ loading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      user_id: this.$route.params.user_id, // 当前用户 ID
      targetUser_id: this.$route.params.targetUser_id, // 对方用户 ID
      targetUser: {}, // 对方用户信息
      messages: [], // 消息列表
      newMessage: '', // 新消息内容
      profile_picture: '', // 当前用户头像
      loading: false, // 发送消息加载状态
    };
  },
  created() {
    if (!this.$route.params.user_id || !this.$route.params.targetUser_id) {
      ElMessage.error("无法获取用户ID，请重新登录或联系管理员");
      return;
    }
    this.fetchCurrentUserInfo();
    this.fetchTargetUserInfo();
    this.fetchMessages();
  },
  methods: {
    // 获取当前用户信息
    async fetchCurrentUserInfo() {
      try {
        const response = await axios.get(`http://localhost:8080/v1/user/${this.user_id}`);
        this.profile_picture = response.data.profile_picture;
      } catch (error) {
        console.error("获取当前用户信息失败", error);
        ElMessage.error("获取当前用户信息失败，请检查网络连接");
      }
    },

    // 获取目标用户信息
    async fetchTargetUserInfo() {
      try {
        const response = await axios.get(`http://localhost:8080/v1/user/${this.targetUser_id}`);
        this.targetUser = response.data;
      } catch (error) {
        console.error("获取目标用户信息失败", error);
        ElMessage.error("获取目标用户信息失败，请检查网络连接");
      }
    },

    // 获取聊天消息
    async fetchMessages() {
      try {
        const response = await axios.get(
          `http://localhost:8080/messages/conversation/${this.user_id}/${this.targetUser_id}`
        );
        this.messages = response.data.map(msg => ({
          ...msg,
          sender: String(msg.sender), // 确保 sender 是字符串（如果后端返回数字类型）
          timestamp: new Date(msg.timestamp).toISOString(),
        }));
        this.scrollToBottom(); // 滚动到最底部
      } catch (error) {
        console.error("获取消息失败", error);
        ElMessage.error("获取消息失败，请检查网络连接");
      }
    },

    // 发送消息
    async sendMessage() {
      if (this.newMessage.trim() === '') return;

      this.loading = true;
      try {
        const response = await axios.post(
          `http://localhost:8080/messages/send`,
          {
            sender: this.user_id,
            receiver: this.targetUser_id,
            content: this.newMessage,
          },
          {
            headers: {
              'Content-Type': 'application/json',
            },
          }
        );

        this.messages.push({
          id: response.data.id,
          content: this.newMessage,
          timestamp: new Date().toISOString(),
          sender: this.user_id,
        });

        this.newMessage = ''; // 清空输入框
        this.scrollToBottom(); // 滚动到底部
      } catch (error) {
        console.error("发送消息失败", error);
        ElMessage.error("发送消息失败，请检查网络连接");
      } finally {
        this.loading = false;
      }
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const chatMessages = this.$refs.chatMessages;
        if (chatMessages) {
          chatMessages.scrollTop = chatMessages.scrollHeight;
        }
      });
    },

    // 格式化日期
    formatDate(date) {
      const d = new Date(date);
      return `${d.toLocaleDateString()} ${d.toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
      })}`;
    },
  },
};
</script>

<style scoped>
.private-message {
  font-family: 'Arial', sans-serif;
  background: #f4f4f9;
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  justify-content: flex-end;
}

.chat-header {
  font-size: 1.4em;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.chat-messages {
  overflow-y: auto;
  flex-grow: 1;
  padding: 0 10px;
}

.message-card {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.message-card.my-message {
  flex-direction: row-reverse; /* 自己的消息在右侧 */
}

.message-card.other-message {
  flex-direction: row; /* 对方的消息在左侧 */
}

.message-card-body {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 12px;
  max-width: 70%;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.my-message .message-card-body {
  background-color: #d9fdd3; /* 自己的消息的背景色 */
}

.other-message .message-card-body {
  background-color: #f1f1f1; /* 对方消息的背景色 */
}

.message-avatar {
  margin: 0 10px;
}

.message-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.message-content {
  font-size: 16px;
  color: #555;
  word-wrap: break-word;
}

.message-meta {
  margin-top: 8px;
  font-size: 12px;
  color: #aaa;
  text-align: right;
}

.chat-input {
  display: flex;
  background-color: #fff;
  border-radius: 20px;
  padding: 12px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.chat-input input {
  flex-grow: 1;
  border: none;
  padding: 12px;
  border-radius: 15px;
  font-size: 14px;
  background-color: #f1f1f1;
  margin-right: 10px;
}

.chat-input button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 15px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 14px;
}

.chat-input button:hover {
  background-color: #45a049;
}
</style>
